<template>
  <div>
    <header class="je-header">
      <div
        @tap="goBack($event)"
        class="back-btn mui-action-back"
      >
        <i class="jeicon jeicon-angle-left" />
      </div>
      <div class="title">
        任务交办
      </div>
      <div
        v-if="type.value === 'send'"
        @tap="deleteItem"
        class="extra je-audio-btn"
      >
        删除
      </div>
      <div
        v-else
        class="extra"
      />
    </header>
    <div class="transaction_detail-wrp">
      <div class="detail_content">
        <div class="detail_title">
          {{ data.TASK_BT }}
        </div>
        <div class="ky martop10">
          <div class="value">
            发布人
          </div>
          <div
            v-if="type.value === 'send'"
            class="label"
          >
            {{ data.SY_CREATEUSERNAME }}
          </div>
          <div
            v-else
            class="label"
          >
            {{ data.JOB_RWFQR }}
          </div>
        </div>
        <div class="ky martop10">
          <div class="value">
            任务时间
          </div>
          <div class="label">
            <span>{{ changeDateType(data.TASK_RWKSSJ) }}</span>
            <span v-if="data.TASK_YQWCSJ">至 {{ changeDateType(data.TASK_YQWCSJ) }}截止</span>
          </div>
        </div>
        <div class="martop10 content_nr">
          {{ data.TASK_RWNR }}
        </div>
      </div>
      <div
        v-if="downloadList.totalList.length > 0"
        class="detail_content download_list"
      >
        <p class="list_title">
          相关附件
        </p>
        <!-- 非图片列表 -->
        <div
          v-for="(item, index) in downloadList.otherList"
          :key="index"
          @tap="download(item)"
          class="download_items je-audio-btn"
        >
          <div v-html="icon(item)" />
          <p class="filename">
            {{ item.name }}
          </p>
        </div>
        <!-- 图片列表 -->
        <div
          class="img_list"
        >
          <!-- @tap="fullScreen(img.path)" -->
          <div
            v-for="(img, index) in downloadList.imgList"
            :key="index"
            @tap="download(img)"
            class="img_list_item je-audio-btn"
          >
            <img :src="getFullUrl(img)">
          </div>
          <!-- 占位div -->
          <div
            v-for="(img, index) in downloadList.emptyList"
            :key="index"
            class="img_list_item"
          />
        </div>
      </div>
      <div
        v-else
        class="detail_content download_list"
      >
        <p class="list_title">
          相关附件
        </p>
        <p class="nodata">
          暂无附件
        </p>
      </div>
      <div
        v-if="type.value === 'send'"
        class="detail_content person_list"
      >
        <p class="list_title">
          执行情况
        </p>
        <transaction-detail-items
          v-for="(item, index) in userList"
          :key="index"
          :data="item"
        />
      </div>
      <float-btn
        v-if="data.JOBMX_SFLQRW !== '1' && type.value === 'task'"
        @tap="handleReceiveTask"
        type="text"
        text="领取"
      />
      <float-btn
        v-else-if="data.JOBMX_SFWCRW !== '1' && type.value === 'task'"
        @tap="handleCompleteTask"
        type="text"
        text="完成"
      />
    </div>
    <PreImage
      :imageItem="imgItem"
      :show="showBig"
      @scaleImg="setSmall"
    />
  </div>
</template>

<script>
import sqlNode, { EXP_TYPE } from '@/helper/safetySqlUtil';
import TransactionDetailItems from '../../components/transactiondetailitems';
import floatBtn from '@/components/floatbtn';
import PreImage from '@/components/bigImage';

export default {
  name: 'TransactionDetail',
  components: {
    TransactionDetailItems,
    floatBtn,
    PreImage,
  },
  data() {
    return {
      loading: false,
      userList: [],
      data: {},
      downloadList: {
        totalList: [],
        imgList: [],
        otherList: [],
        emptyList: [],
      },
      type: '',
      JOBMX_SFLQRW: '',
      JOBMX_SFWCRW: '',
      imgItem: {},
      showBig: false,
    };
  },
  created() {
    const { item, type } = this.$route.query;
    this.data = item;
    this.JOBMX_SFLQRW = item.JOBMX_SFLQRW;
    this.JOBMX_SFWCRW = item.JOBMX_SFWCRW;
    this.type = type;
    if (item.TASK_XGFJ) {
      this.downloadList.totalList = JSON.parse(item.TASK_XGFJ) || [];
    }
    this.downloadList.totalList.forEach((item) => {
      if ('jpg,jpeg,png,gif,JPG,JPEG,BMP,bmp'.indexOf(this.utilType(item.name)) > -1) {
        this.downloadList.imgList.push(item);
      } else {
        this.downloadList.otherList.push(item);
      }
    });
    const emptylength = 4 - (this.downloadList.imgList.length % 4);
    for (let i = 0; i < emptylength; i++) {
      this.downloadList.emptyList.push(i);
    }
  },
  mounted() {
    this.searchlist();
  },
  methods: {
    goBack(event) {
      event.stopPropagation();
      if (this.data.JOBMX_SFLQRW === this.JOBMX_SFLQRW && this.data.JOBMX_SFWCRW === this.JOBMX_SFWCRW) {
        mui.back();
        // this.$router.go(-1);
      } else {
        // const parent = plus.webview.currentWebview().opener();
        // mui.fire(parent, 'changeStatues');
        mui.back();
        // this.$router.go(-1);
      }
    },
    deleteItem() {
      const btnArray = ['取消', '删除'];
      mui.confirm('确定删除吗?', '', btnArray, (e) => {
        if (e.index === 1) {
          JE.ajax({
            url: '/je/job/job/deleteTask',
            params: {
              JE_SYS_TASK_ID: this.data.JE_SYS_TASK_ID,
              TASK_TASKFS_CODE: this.data.TASK_TASKFS_CODE,
            },
          }).then(() => {
            this.$router.push({
              path: '/JE-PLUGIN-TRANSACTION/list',
              query: {
                type: 'refreshList',
              },
            });
            JE.msg('删除成功');
          }).catch(() => {
            JE.msg('删除失败');
          });
        }
      });
    },
    searchlist() {
      const params = {
        whereSql: `AND JE_SYS_TASK_ID = '${this.data.JE_SYS_TASK_ID}'`,
        ...sqlNode.buildSqls({
          custom: [
            sqlNode.buildCustomSql({
              code: 'JE_SYS_TASK_ID',
              type: EXP_TYPE.eq,
              value: this.data.JE_SYS_TASK_ID,
            }),
          ],
        }),
        orderSql: 'order by SY_CREATETIME',
        tableCode: 'JE_SYS_JOB_V',
        limit: '-1',
      };
      // TODO Sql  zmp
      JE.ajax({
        url: '/je/load',
        params,
      }).then((data) => {
        this.userList = data.rows;
      });
    },
    // 修改日期格式
    changeDateType(date) {
      if (!date) return;
      const ymd = date.split(' ')[0];
      if (date.split(' ').length < 2) {
        return `${ymd} 0点`;
      }
      const h = date.split(' ')[1].split(':')[0];
      return `${ymd} ${h}点`;
    },
    download(item) {
      const that = this;
      // const path = item.src ? item.path : item.src;
      const path = item.path ? JE.getFileUrl(item.path, 'down') : item.src;
      if (window.plus) { // 支持plus
        // const fileName = `docs${path.substring(path.lastIndexOf('/'))}`;
        const fileName = item.name;
        // 判断文件是否已经下载
        plus.io.resolveLocalFileSystemURL(JE.getBasicPath(`download/${fileName}`),
          (file) => { // 如果已存在文件，则打开文件
            if (file.isFile) {
              // JE.msg('正在打开文件...');
              // plus.runtime.openFile(JE.getBasicPath(`download/${fileName}`));
              const filetype = item.name.substring(item.name.lastIndexOf('.') + 1);
              if ('jpg,jpeg,png,gif,JPG,JPEG,BMP,bmp'.indexOf(filetype) > -1) {
                that.fullScreen(item);
              } else {
                JE.msg('正在打开文件...');
                plus.runtime.openFile(JE.getBasicPath(`download/${fileName}`));
              }
            }
          }, () => { // 如果未下载文件，则下载后打开文件
            JE.download({
              url: path,
              fileName,
              callback() {
                JE.closeWaiting();
                JE.msg('下载完成！');
              },
            });
          });
      } else { // 不支持plus
        window.open(path);
      }
    },
    // 领取任务
    handleReceiveTask() {
      JE.showWaiting();
      JE.ajax({
        url: '/je/job/job/receiveTask',
        params: {
          JE_SYS_JOB_ID: this.data.JE_SYS_JOB_ID,
          JOB_RWFQRID: this.data.JOB_RWFQRID,
          TASK_TASKFS_CODE: this.data.TASK_TASKFS_CODE,
          JE_SYS_TASK_ID: this.data.JE_SYS_TASK_ID,
        },
      }).then(() => {
        JE.closeWaiting();
        this.data.JOBMX_SFLQRW = '1';
        JE.msg('领取成功');
        this.$router.push({
          path: '/JE-PLUGIN-TRANSACTION/list',
          query: {
            type: 'changeStatues',
          },
        });
      }).catch(() => {
        JE.closeWaiting();
      });
    },
    // 完成任务
    handleCompleteTask() {
      JE.showWaiting();
      JE.ajax({
        url: '/je/job/job/finishTask',
        params: {
          JE_SYS_JOB_ID: this.data.JE_SYS_JOB_ID,
          JOB_RWFQRID: this.data.JOB_RWFQRID,
          TASK_TASKFS_CODE: this.data.TASK_TASKFS_CODE,
          JE_SYS_TASK_ID: this.data.JE_SYS_TASK_ID,
        },
      }).then(() => {
        JE.closeWaiting();
        this.data.JOBMX_SFWCRW = '1';
        JE.msg('任务已完成');
        JE.refreshBadge({ badge: -1, code: 'JE-PLUGIN-TRANSACTION', type: 'TRANSACTION' });
        this.$router.push({
          path: '/JE-PLUGIN-TRANSACTION/list',
          query: {
            type: 'changeStatues',
          },
        });
      }).catch(() => {
        JE.closeWaiting();
      });
    },
    utilType(path) {
      return path.substring(path.lastIndexOf('.') + 1);
    },
    // 获取图片路径
    getFullUrl(img) {
      // if (img.src) {
      //   return img.src;
      // }
      // return JE.buildURL(JE.getFileUrl(img.path));
      return JE.getFileUrl(img.path, 'preview') || img.src;
    },
    // 全屏
    fullScreen(item) {
      this.showBig = true;
      this.imgItem = item; // this.getFullUrl(path);
    },
    // 取消全屏
    setSmall() {
      this.showBig = false;
    },
    icon(item) {
      let icon = '';
      let color = '';
      const type = this.utilType(item.name);
      if ('doc,docx'.indexOf(type) > -1) {
        icon = 'word';
        color = '2A5699';
      } else
      if ('xls,xlsx'.indexOf(type) > -1) {
        icon = 'excel';
        color = '107B0F';
      } else
      if ('pdf'.indexOf(type) > -1) {
        icon = 'pdf';
        color = 'DC2E1B';
      } else
      if ('ppt'.indexOf(type) > -1) {
        icon = 'pdf';
        color = 'D24625';
      } else
      if ('txt'.indexOf(type) > -1) {
        icon = 'txt';
        color = 'F39205';
      } else {
        icon = 'unknownfile';
        // color = 'F39205';
      }
      return `<i class="jeicon jeicon-${icon}" style="color: #${color}">`;
    },
  },
};
</script>

<style lang="less" scoped>
  @import '~@/theme/index.less';
  .transaction_detail-wrp {
    position: absolute;
    top: unit(45 * @hd, px);
    right: 0;
    bottom: 0;
    left: 0;
    background: #ffffff;
    color: @color-text-base;
    overflow: auto;
    p {
      margin: 0;
    }
    .detail_content {
      padding: 10 * @hd 15 * @hd;
      padding-bottom: 50 * @hd;
      .martop10 {
        margin-top: 10 * @hd;
      }
      .detail_title {
        font-size: @font-size-heading;
      }
      .ky {
        display: flex;
        align-items: center;
        justify-content: flex-start;
        font-size: 14 * @hd;
        .value {
          color: #A9ABA9;
          width: 70 * @hd;
        }
        .label {
          flex: 1;
        }
      }
      .content_nr {
        font-size: 16 * @hd;
      }
      .list_title {
        color: #A9ABA9;
        font-size: 14 * @hd;
        margin-bottom: 10 * @hd;
      }
      &.download_list {
        border-top: 10px solid rgba(245,245,245,1);
        .download_items {
          display: flex;
          align-items: center;
          justify-content: flex-start;
          padding: 10 * @hd 0;
          padding-right: 20 * @hd;
          position: relative;
          .jeicon{
            font-size: 30 * @hd;
          }
          .filename {
            color: @color-text-base;
            font-size: 14 * @hd;
            flex: 1;
            margin-left: 10px;
          }
          &:active {
            background: #eaebef;;
          }
        }
        .img_list {
          display: flex;
          justify-content: space-between;
          flex-wrap: wrap;
          margin-top: 5 * @hd;
          .img_list_item {
              width: 70 * @hd;
              height: 64 * @hd;
              margin-bottom: 10 * @hd;
            > img{
              width: 100%;
              height: 100%;
            }
          }
        }
        .nodata {
          text-align: center;
          font-size: 14 * @hd;
          color: #A9ABA9;
        }
      }
      &.person_list {
        border-top: 10px solid #f5f5f5;
      }
    }
  }
</style>
<style lang="less">
  @import "~@/theme/index.less";
  header.je-header {
    height: unit(45 * @hd, px);
    // box-sizing: content-box;
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #ffffff;
    background-color: #536dfe;
    padding: 0 30px;
    font-size: 32px;
    position: fixed;
    width: 100%;
    top: 0;
    left: 0;
    z-index: 1000;
    .back-btn {
      .back-text {
        margin-left: 5px;
      }
      i {
        color: #ffffff;
        font-size: 32px;
      }
    }
    .title {
      text-align: center;
    }
    .extra {
      text-align: right;
    }
    //  mainTitle 模式下 中间区域最大自适应，左右两边补充
    &:not(.main-title) > * {
      flex: 1;
    }
    .title {
      flex: 1;
    }
    &.hide-btn {
      padding-left: 15px;
      padding-right: 18px;
    }
  .je-content{
    padding-top: 0!important;
  }
    // &.main-title {
    // }
  }
  .jeicon{
    font-size: 30 * @hd;
  }
</style>
